package com.gmrz.uap.model;

import com.jfinal.plugin.activerecord.generator.ColumnMeta;
import com.jfinal.plugin.activerecord.generator.TableMeta;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class _BuildDatabaseConst {
    private List<TableMeta> tableMetaList;
    private String databaseConstPath;

    public _BuildDatabaseConst(List<TableMeta> tableMetaList, String databaseConstPath) {
        this.tableMetaList = tableMetaList;
        this.databaseConstPath = databaseConstPath;
    }

    public void build() throws IOException {
        StringBuffer sb = new StringBuffer();
        sb.append("package com.gmrz.uap.common;\npublic class DBCommon {\n");

        for (TableMeta tableMeta : tableMetaList) {
            String tableName = tableMeta.name.toLowerCase().replaceFirst("t_", "").toUpperCase();

            sb.append("public static final String ").append("TABLE_").append(tableName).append(" = ").append("\"").append(tableMeta.name.toLowerCase()).append("\"").append(";\n");
            for (ColumnMeta columnMeta : tableMeta.columnMetas) {
                sb.append("public static final String ")
                        .append("TABLE_")
                        .append(tableName)
                        .append("_")
                        .append("COLUMN_")
                        .append(columnMeta.name.toUpperCase())
                        .append(" = ")
                        .append("\"")
                        .append(columnMeta.name.toLowerCase())
                        .append("\"").append(";")
                        .append("\n");
            }
            sb.append("\n\n\n\n\n");
        }

        sb.append("}");
        IOUtils.write(sb.toString(), new FileOutputStream(new File(databaseConstPath)), "utf-8");
    }
}
